# -*- coding: utf-8 -*-
# @File     : api.py
# @Author   : bingjia
# @Time     : 2020/8/7 9:14
# @Desc     : 状态api视图

from django.conf import settings
from collections import OrderedDict
from django.views.decorators.cache import cache_page

from ..base.api import viewsets
from ..base.api import response

from . import permissions
from . import services

CACHE_TIMEOUT = getattr(settings, "STATS_CACHE_TIMEOUT", 0)


class BaseStatsViewSet(viewsets.ViewSet):
    """
    基础状态视图
    """

    @property
    def _cache_timeout(self):
        return CACHE_TIMEOUT

    def dispatch(self, *args, **kwargs):
        return cache_page(self._cache_timeout)(super().dispatch)(*args, **kwargs)


class SystemStatsViewSet(BaseStatsViewSet):
    """
    系统状态视图
    """
    permission_classes = (permissions.SystemStatsPermission,)

    def list(self, request, **kwargs):
        """
        获取项目总体状态信息
        :return:
        """
        resources = OrderedDict()
        resources["totals"] = services.get_total_public_resources()
        resources["checks"] = services.get_checks_public_resources()
        resources["infos"] = services.get_infos_public_resources()
        resources["project_list"] = services.get_project_list_resources()

        return response.Ok(resources)
